package com.java1412.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author java1412
 * @since 2024-04-01 17:31:33
 */
@Component
public class MyFilter extends ZuulFilter {
    // 过滤器类型，返回一个pre，表示在路由之前执行
    @Override
    public String filterType() {
        return "pre";
    }

    // 过滤器执行顺序
    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true; // 永远过滤
    }

    // 过滤的逻辑过程，将来可以访问数据库，redis
    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        System.out.println(request.getMethod() + " >>> " + request.getRequestURL().toString());
        // 获取请求的令牌
        String accessToken = request.getParameter("token");
        if (null == accessToken) {
            // 没有登录，不能路由(不能访问某个微服务节点)
            System.out.println("没有token");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("token is empty");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;// 调用后续的微服务
        }
        System.out.println("有token");
        return ctx;
    }
}
